function toTreeData(data) {
  const newData = data
    .filter(item => item.parentId === '0')
    .map(item => ({
      code: item.orgCode,
      key: item.orgId,
      value: item.orgCode,
      title: item.orgName,
      children: []
    }));
  const hasParentLevelArr = data.filter(item => item.parentId);

  function loop(_newData, restArr) {
    const data2 = _newData.map(item => {
      const children = restArr.filter(child => child.parentId === item.key);
      const notCurrentLevelArr = restArr.filter(
        child => child.parentId !== item.key
      );
      if (children.length > 0) {
        let newChildren = children.map(_item => ({
          code: _item.orgCode,
          key: _item.orgId,
          value: _item.orgCode,
          title: _item.orgName,
          children: []
        }));
        if (notCurrentLevelArr.length > 0) {
          newChildren = loop(newChildren, notCurrentLevelArr);
        }

        const newItem = {
          ...item,
          children: newChildren
        };
        return newItem;
      }

      return {
        ...item
      };
    });
    return data2;
  }

  return loop(newData, hasParentLevelArr);
}

export default toTreeData;
